package demo2;

public class HashBuckPlus<K,V> {
    static class Node<K,V>{
        public K key;
        public V value;
        public Node<K,V> next;

        public Node(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }
    public Node<K,V>[] array;
    public int usedSize;
    public static final double LOAD_FACTOR = 0.75;//负载因子

    public HashBuckPlus() {
        array = (Node<K,V>[])new Node[10];
    }
    public void push(K key,V value){
        //将K类型转成int类型
        int hash = Math.abs(key.hashCode());
        int index = hash % array.length;
        Node<K,V> cur = array[index];
        while (cur != null) {
            if(cur.key.equals(key)) {
                cur.value = value;
                return;
            }
            cur = cur.next;
        }
        Node<K,V> newNode = new Node<K,V>(key,value);
        newNode.next = array[index];
        array[index] = newNode;
        usedSize++;
        //计算负载因子
        if(calcLOADFACTOR() >= LOAD_FACTOR) {
            //扩容
            //重新哈希一遍，因为有些数据的哈希地址发生变化
            resize();
        }
    }
    private void resize() {
        Node<K,V>[] newArray = (Node<K,V>[])new Node[array.length*2];
        //重新哈希，开始遍历数组中的每个链表
        for (int i = 0; i < array.length; i++) {
            Node<K,V> cur = array[i];
            while (cur != null) {
                int hash = Math.abs(cur.key.hashCode());
                int newIndex = hash % newArray.length;
                //在新数组中进行头插法
                Node<K,V> curN = cur.next;//curN用来标记cur的下一个节点
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curN;
            }
        }
        array = newArray;
    }

    private double calcLOADFACTOR() {
        return usedSize * 1.0 / array.length;
    }
    public V get(K key){
        int hash = Math.abs(key.hashCode());
        int index = hash % array.length;
        Node<K,V> node = array[index];
        while (node != null) {
            if(node.key.equals(key)) {
                return node.value;
            }
            node = node.next;
        }
        return null;
    }
}